<script setup lang="ts">
import { request } from '@/api'
import axios from 'axios'
import b64toBlob from 'b64-to-blob'
import { showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'

// 是否显示 拍照,相册交互弹框
const showAvatarSheet = ref(false)

const actions = [{ name: '拍照' }, { name: '相册' }]

const onCancel = () => {
  showToast('取消')
}

const onSelect = async (action: ActionSheetAction, index: number) => {
  if (index == 0) {
    // console.log('拍照')
    const res = await mk.pickerCamera()
    console.log('拍照', res)
  } else if (index == 1) {
    // console.log('相册')
    const res = await mk.pickerPhoto()
    // console.log('相册', res)
    // base64 转 二进制
    const img = b64toBlob(res, 'image/jpeg')
    showAvatarSheet.value = false
    // 创建一个 装载数据的 FormData 对象
    const fd = new FormData()
    // 追加数据
    // file key
    // img 数据
    // 参数3 名字
    fd.append('file', img, Date.now() + '.jpeg')
    // 调用上传接口,根据接口文档设置地址和方法,FormData 设置到 参数 2 即可
    const uploadRes = await request.post<MkResponse<{ avatar: string }>>(
      'member/profile/avatar',
      fd,
    )
    // console.log(uploadRes.data.result)
    // 修改页面的显示
    profile.value.avatar = uploadRes.data.result.avatar
    // 获取 保存在 鸿蒙缓存中 用户信息
    const user = mk.queryUser()
    // 修改用户信息的头像 为上传成功之后的头像
    user.avatar = uploadRes.data.result.avatar
    // 更新鸿蒙端的头像
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  }
}

// 生日弹层相关-------------------
const showBirthdayPop = ref(false)
const currentDate = ref(['2000', '05', '12'])
const minDate = new Date(1970, 1, 1)
const maxDate = new Date(2025, 1, 1)
const onBirthdayConfirm = () => {
  // console.log(currentDate.value)
  showBirthdayPop.value = false
  profile.value.birthday = currentDate.value.join('-')
}

// 省市区弹层
const areaList = ref<AreaColumns>({} as AreaColumns)
const showAreaPop = ref(false)
const selectArea = ref('')
onMounted(async () => {
  const res = await mk.getAreaColumns()
  areaList.value = res
})
const onAreaConfirm = ({ selectedValues, selectedOptions, selectedIndexes }) => {
  showAreaPop.value = false
  // console.log(selectedValues)
  // console.log(selectedOptions)
  // console.log(selectedIndexes)
  const res = selectedOptions.map((v) => {
    return v.text
  })
  // 修改页面渲染的省市区
  profile.value.fullLocation = res.join(' ')
  // 修改提交数据中的 省市区编码
  profile.value.provinceCode = selectedValues[0]
  profile.value.cityCode = selectedValues[1]
  profile.value.countryCode = selectedValues[2]
}

// 职业选择器
const columns = [
  { text: '医生', value: '医生' },
  { text: '老师', value: '老师' },
  { text: '程序员', value: '程序员' },
  { text: '理发师', value: '理发师' },
  { text: '主播', value: '主播' },
  { text: '软件工程师', value: '软件工程师' },
]
const selectJob = ref<string[]>([])
const onJobConfirm = ({ selectedValues }) => {
  // showToast(`当前值: ${selectedValues.join(',')}`)
  showJobPop.value = false
  profile.value.profession = selectedValues.join('')
}
const showJobPop = ref(false)

// 获取用户信息
const profile = ref({} as ProfileInfo)
onMounted(async () => {
  const res = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  // console.log(res.data.result)
  profile.value = res.data.result
  // 生日
  currentDate.value = profile.value.birthday.split('-')
  // 设置给 绑定的职业数据
  selectJob.value = [profile.value.profession]
})

// 保存资料----------------------
const onSubmit = async () => {
  showLoadingToast({
    message: '加载中...',
  })
  // 提交数据
  const res = await request.put<MkResponse<ProfileInfo>>('member/profile', profile.value)
  mk.updateUser(res.data.result)
  showToast('更新成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

    <!-- 选择拍照 还是 相册 -->
    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
    />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        v-model="profile.birthday"
        @click="showBirthdayPop = true"
        label="生日"
        readonly
        placeholder="请选择日期"
      ></van-field>
      <van-field
        v-model="profile.fullLocation"
        @click="showAreaPop = true"
        label="所在地"
        readonly
        placeholder="请选择所在地"
      ></van-field>
      <van-field
        v-model="profile.profession"
        @click="showJobPop = true"
        label="职业"
        readonly
        placeholder="请选择职业"
      ></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button @click="onSubmit" round block type="primary"> 保存资料 </van-button>
    </div>
    <!-- 生日弹层 -->
    <van-popup v-model:show="showBirthdayPop" round position="bottom">
      <van-date-picker
        v-model="currentDate"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onBirthdayConfirm"
        @cancel="showBirthdayPop = false"
      />
    </van-popup>
    <!-- 省市区弹层 -->
    <van-popup v-model:show="showAreaPop" round position="bottom">
      <van-area
        :area-list="areaList"
        title="选择省市区"
        @confirm="onAreaConfirm"
        @cancel="showAreaPop = false"
      />
    </van-popup>
    <!-- 职业弹层 -->
    <van-popup v-model:show="showJobPop" round position="bottom">
      <van-picker
        v-model="selectJob"
        title="标题"
        :columns="columns"
        @confirm="onJobConfirm"
        @cancel="showJobPop = false"
      />
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
